package com.xyw.his00.aspect;

import com.alibaba.fastjson.JSONObject;
import com.xyw.his00.mapper.OperateLogMapper;
import com.xyw.his00.pojo.dbpojo.OperateLog;
import com.xyw.his00.utils.NumberUtils.TokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Slf4j
@Aspect
@Order(1)

public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    //获取当前请求的请求头中的信息
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Around("@annotation(com.xyw.his00.anno.OptionLog)")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        //1。获取操作人员名称 从token中获取操作人员的名称
        String token=httpServletRequest.getHeader("token");
        if(token==null){
            return  new String("失败了orz");
        }
       Claims claims=TokenUtil.verify(token);
       String userName= (String) claims.get("userName");
    if(claims!=null){
        System.out.println("User: " + claims.get("userName"));
        System.out.println("Expiration: " + claims.getExpiration());
    }
        //2.获取操作时间
        LocalDateTime localDateTime=LocalDateTime.now();
        //3.获取操作类名
        String className=proceedingJoinPoint.getTarget().getClass().getName();
        //4.获取操作方法名
       String name= proceedingJoinPoint.getSignature().getName();
        //5.获取操作方法参数
        Object [] arg=proceedingJoinPoint.getArgs();
        String args= Arrays.toString(arg);
        long beginTime=System.currentTimeMillis();
        //6.获取操作方法的返回值
        Object resultLog=proceedingJoinPoint.proceed();
        String jsonResult= JSONObject.toJSONString(resultLog);
        //7.操作耗时
        long endTime=System.currentTimeMillis();
        long duration=endTime-beginTime;
        operateLogMapper.insert(new OperateLog(null,userName,localDateTime,className,name,args,jsonResult,duration));
        log.info(jsonResult);
     return  resultLog;
    }
}
